package com.kczd.jinlan.view;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.kczd.jinlan.R;
import com.kczd.jinlan.SysApplication;
import com.kczd.jinlan.model.User;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.view.classify.fragment.ClassificationFragment;
import com.kczd.jinlan.view.mine.fragment.MyFragment;
import com.kczd.jinlan.view.order.OrderFragment;
import com.kczd.jinlan.view.shopcar.ShoppingActivity;
import com.kczd.jinlan.view.shouye.fragment.ShangchengFragment;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.litepal.tablemanager.Connector;

import static com.kczd.jinlan.R.id.iv_make;


/**
 * yang_g
 * 程序主入口
 * Created by Administrator on 2017/5/15.
 */

public class MainActivity extends FragmentActivity  {

    private TextView tvMain, tvDynamic, tvMessage, tvPerson;//底部四个TextView

    //要切换显示的四个Fragment
    private ShangchengFragment mainFragment;
    private ClassificationFragment dynamicFragment;
    private OrderFragment messageFragment;
    private MyFragment personFragment;

    private int currentId = R.id.tv_main;// 当前选中id,默认是主页

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        SysApplication.getInstance().addActivity(this);

        initImageLoader();
        SQLiteDatabase db = Connector.getDatabase();

        Config.user = (User)Config.readObject(getBaseContext());
        // 检查登陆
        if(Config.user==null){
            startActivity(new Intent(MainActivity.this, LoginActivity.class));//打开登录页面
        }

        tvMain = (TextView) findViewById(R.id.tv_main);
        tvMain.setSelected(true);//首页默认选中
        tvDynamic = (TextView) findViewById(R.id.tv_dynamic);
        tvMessage = (TextView) findViewById(R.id.tv_message);
        tvPerson = (TextView) findViewById(R.id.tv_person);

        /**
         * 默认加载首页
         */
        mainFragment = new ShangchengFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.main_container, mainFragment).commit();

        tvMain.setOnClickListener(tabClickListener);
        tvDynamic.setOnClickListener(tabClickListener);
        tvMessage.setOnClickListener(tabClickListener);
        tvPerson.setOnClickListener(tabClickListener);
        findViewById(iv_make).setOnClickListener(onClickListener);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case iv_make:
                    Intent intent = new Intent(MainActivity.this, ShoppingActivity.class);
                    startActivity(intent);
                    break;
            }
        }
    };

    private View.OnClickListener tabClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() != currentId) {//如果当前选中跟上次选中的一样,不需要处理
                changeSelect(v.getId());//改变图标跟文字颜色的选中
                changeFragment(v.getId());//fragment的切换
                currentId = v.getId();//设置选中id
            }
        }
    };

    /**
     * 改变fragment的显示
     *
     * @param resId
     */
    private void changeFragment(int resId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();//开启一个Fragment事务

        hideFragments(transaction);//隐藏所有fragment
        if (resId == R.id.tv_main) {//商城
            if (mainFragment == null) {//如果为空先添加进来.不为空直接显示
                mainFragment = new ShangchengFragment();
                transaction.add(R.id.main_container, mainFragment);
            } else {
                transaction.show(mainFragment);
            }
        } else if (resId == R.id.tv_dynamic) {//分类
            if (dynamicFragment == null) {
                dynamicFragment = new ClassificationFragment();
                transaction.add(R.id.main_container, dynamicFragment);
            } else {
                transaction.show(dynamicFragment);
            }
        } else if (resId == R.id.tv_message) {//订单
            if (messageFragment == null) {
                messageFragment = new OrderFragment();
                transaction.add(R.id.main_container, messageFragment);
            } else {
                transaction.show(messageFragment);
            }
        } else if (resId == R.id.tv_person) {//我的
            if (personFragment == null) {
                personFragment = new MyFragment();
                transaction.add(R.id.main_container, personFragment);
            } else {
                transaction.show(personFragment);
            }
        }
        transaction.commit();//一定要记得提交事务
    }

    /**
     * 显示之前隐藏所有fragment
     *
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mainFragment != null)//不为空才隐藏,如果不判断第一次会有空指针异常
            transaction.hide(mainFragment);
        if (dynamicFragment != null)
            transaction.hide(dynamicFragment);
        if (messageFragment != null)
            transaction.hide(messageFragment);
        if (personFragment != null)
            transaction.hide(personFragment);
    }

    /**
     * 改变TextView选中颜色
     *
     * @param resId
     */
    private void changeSelect(int resId) {
        tvMain.setSelected(false);
        tvDynamic.setSelected(false);
        tvMessage.setSelected(false);
        tvPerson.setSelected(false);

        switch (resId) {
            case R.id.tv_main:
                tvMain.setSelected(true);
                break;
            case R.id.tv_dynamic:
                tvDynamic.setSelected(true);
                break;
            case R.id.tv_message:
                tvMessage.setSelected(true);
                break;
            case R.id.tv_person:
                tvPerson.setSelected(true);
                break;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        PackageManager pm = getPackageManager();
        ResolveInfo homeInfo =
                pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            ActivityInfo ai = homeInfo.activityInfo;
            Intent startIntent = new Intent(Intent.ACTION_MAIN);
            startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
            startActivitySafely(startIntent);
            Toast.makeText(this, "温馨提醒：金兰蔬菜在后台运行", Toast.LENGTH_LONG).show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private void startActivitySafely(Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, e.toString(),
                    Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Toast.makeText(this, e.toString(),
                    Toast.LENGTH_SHORT).show();
        }
    }
    public void initImageLoader() {
        //创建默认的ImageLoader配置参数
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                //.writeDebugLogs() //打印log信息
                .build();

        //Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(configuration);
    }
}